//
//  SpecialStarDetailVC.swift
//  甜言蜜语
//
//  Created by yingli_yanfa_liuxingyu on 16/8/17.
//  Copyright © 2016年 wl. All rights reserved.
//

import UIKit
import SVProgressHUD
class SpecialStarDetailVC: UIViewController, UITableViewDataSource, UITableViewDelegate, SpecialStarDetailHeadCellDelegate{

    
    @IBOutlet weak var tableView: UITableView!
    var modelList: specialStarDetailInfo?{
        didSet{
            self.tableView.reloadData()
            self.initRightItem()
        }
    }
    var msg: regiestInfo?
    var chooseAllBtn: Bool!
    var chooserecruitBtn: Bool!
    var id: String = ""//企业的id
    var topicsHeight: CGFloat = 0.0
    var isshoucang: Bool?
    var allBtn: UIButton!
    var recruitBtn: UIButton!
    override func viewDidLoad() {
        super.viewDidLoad()
        publicMethod.setHUDStyle()
        self.title = "企业主页"
        self.tableView.delegate = self
        self.tableView.dataSource = self
        
        self.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
        
        let cellNib = UINib(nibName: "SpecialStarDetailHeadCell", bundle: nil)
        self.tableView.registerNib(cellNib, forCellReuseIdentifier: "SpecialStarDetailHeadCell")
        

        publicMethod.hiddleExtendCellForTableView(self.tableView)
        chooseAllBtn = true
        chooserecruitBtn = false
        self.getStarDetailInfo(id)

    }
    override func viewWillDisappear(animated: Bool) {
        SVProgressHUD.dismiss()
        super.viewWillDisappear(animated)
    }
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        self.tabBarController?.tabBar.hidden = true
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    func initRightItem(){
        let img: UIImage?
        if self.modelList?.isshoucang == true{
            img = UIImage(named: "collection_selected")
        }else{
            img = UIImage(named: "collection-white")
        }
        //收藏
        let collectionBtn = UIButton(frame: CGRectMake(0, 0, 20, 20))
        collectionBtn.setBackgroundImage(img, forState: UIControlState.Normal)
        collectionBtn.addTarget(self, action: #selector(self.collectionAction), forControlEvents:  UIControlEvents.TouchUpInside)
        let collection = UIBarButtonItem(customView: collectionBtn)
        //转发
        let ForwardBtn = UIButton(frame: CGRectMake(0, 0, 20, 20))
        ForwardBtn.setBackgroundImage(UIImage(named: "share-1-white"), forState: UIControlState.Normal)
        ForwardBtn.addTarget(self, action: #selector(self.ForwardAction), forControlEvents:  UIControlEvents.TouchUpInside)
        let Forward = UIBarButtonItem(customView: ForwardBtn)
        
        //举报
        let ReportBtn = UIButton(frame: CGRectMake(0, 0, 20, 20))
        ReportBtn.setBackgroundImage(UIImage(named: "Report-white"), forState: UIControlState.Normal)
        ReportBtn.addTarget(self, action: #selector(self.ReportAction), forControlEvents:  UIControlEvents.TouchUpInside)
        let Report = UIBarButtonItem(customView: ReportBtn)
        
        self.navigationItem.rightBarButtonItems = [collection, Forward,Report]
        
        
        
    }
    func collectionAction(){
        self.getSpecitalCollection()
    }
    func ForwardAction(){
        let shareParames = NSMutableDictionary()
        let url = String(format: "%@mxqy/fenxiang/\(id)",BaseUrl)
        
        shareParames.SSDKSetupShareParamsByText("",
                                                images : UIImage(named: "ShareImg.png"),
                                                url : NSURL(string:url),
                                                title : "明星企业",
                                                type : SSDKContentType.Auto)
        
        
        //2.进行分享
        SSUIShareActionSheetStyle.setShareActionSheetStyle(ShareActionSheetStyle.Simple)
        
        ShareSDK.showShareActionSheet(self.view, items: nil  , shareParams: shareParames) { (state : SSDKResponseState, platformType : SSDKPlatformType, userdata : [NSObject : AnyObject]!, contentEnity : SSDKContentEntity!, error : NSError!, end) -> Void in
            
            switch state{
                
            case SSDKResponseState.Success: print("分享成功")
            case SSDKResponseState.Fail:    print("分享失败,错误描述:\(error)")
            case SSDKResponseState.Cancel:  print("分享取消")
                
            default:
                break
            }
        }
        

        
    }
    func ReportAction(){
        self.reportBtnClicked()
    }
    //举报
    func reportBtnClicked(){
        let vc = self.storyboard?.instantiateViewControllerWithIdentifier("ReportVC") as! ReportVC
        vc.id = self.modelList!.id
        self.navigationController?.pushViewController(vc, animated: true)
    }
    //MARK:SpecialStarDetailHeadCellDelegate
    func callBtnSelected(text: String){
        publicMethod.callPhone(text, withSuperView: self.view)
        
    }
    func collectionBtnSelected(text: String){
        if ApplicationDelegate.isLogin(){
            self.getSpecitalCollection()
        }else{
            let sb = UIStoryboard(name: "Login", bundle: nil)
            let vc = sb.instantiateViewControllerWithIdentifier("LoginViewController")
            self.navigationController?.pushViewController(vc, animated: true)
        }
        
    }
    func collectionCompanyStyle(){
        DetailPictureView.MXQYImgDisplay(self.modelList!.unitstyles!, index: (self.modelList?.unitstyles?.count)! - 1)
        
    }
    //MARK:tableviewDataSource
     func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 2
    }
    func tableView(tableView: UITableView,heightForHeaderInSection section: Int) -> CGFloat{
        if section == 0{
            return 0
        }else{
            return 50
        }
        
        
    }
    /**
     自定义HeaderSection，达到当前话题的索引颜色
     是红色
     */
    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section == 0{
            return view
        }else{
             let sectionView = UIView()
            //let allBtn = UIButton()
            allBtn = UIButton(frame: CGRectMake(SCREEN_WIDTH/2-50, 0, 50, 30))
            allBtn.setTitle("全部", forState: UIControlState.Normal)
            allBtn.selected = true
           
           // allBtn.setBackgroundImage(UIImage(named: "spectial1"), forState: UIControlState.Normal)
            
           
            allBtn.setTitleColor(UIColor.redColor(), forState: UIControlState.Normal)
            allBtn .addTarget(self, action: #selector(SpecialStarDetailVC.allBtnClicked), forControlEvents: UIControlEvents.TouchUpInside)
            allBtn.titleLabel?.font = UIFont.systemFontOfSize(14)
            
            //let recruitBtn = UIButton()
            recruitBtn = UIButton(frame: CGRectMake(CGRectGetMaxX(allBtn.frame), 0, 50, 30))
            
            recruitBtn.setTitle("招聘", forState: UIControlState.Normal)
           
            recruitBtn.setTitleColor(UIColor.redColor(), forState: UIControlState.Normal)
           
            //recruitBtn.setBackgroundImage(UIImage(named: "spectial2"), forState: UIControlState.Selected)

            recruitBtn.titleLabel?.font = UIFont.systemFontOfSize(14)
            recruitBtn .addTarget(self, action: #selector(SpecialStarDetailVC.recruitBtnClicked), forControlEvents: UIControlEvents.TouchUpInside)
            sectionView .addSubview(allBtn)
            sectionView .addSubview(recruitBtn)
            return sectionView

        }
        
    }
    
    func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        if(cell.respondsToSelector(Selector("setSeparatorInset:"))) {
            cell.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0)
        }
        if(cell.respondsToSelector(Selector("setLayoutMargins:"))) {
            cell.layoutMargins = UIEdgeInsetsMake(0, 0, 0, 0)
        }
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0{
            if self.modelList == nil{
                return 0
            }else{
                return 1
            }
        }
        if section == 1{
            if chooseAllBtn != nil{
                if chooseAllBtn == true {
                    if self.modelList?.infomations?.count == 0 || self.modelList?.infomations?.count == nil{
                        return 0
                    }else{
                        return Int((self.modelList?.infomations?.count)!)
                    }
                }
            }else{
                return 0
            }
            if chooserecruitBtn != nil{
                if chooserecruitBtn == true{
                    if self.modelList?.recruitments?.count == 0 || self.modelList?.recruitments?.count == nil{
                        return 0
                    }else{
                        return Int((self.modelList?.recruitments?.count)!)
                    }
                }
            }else{
                return 0
            }
            
        }
        return 0

    }
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        if indexPath.section == 0{
            let cell = tableView.dequeueReusableCellWithIdentifier("SpecialStarDetailHeadCell") as! SpecialStarDetailHeadCell
            
            let cellInfo = self.modelList
            cell.setCellContentWithCellInfo(cellInfo)
            return CGFloat(cell.cellHieight)
            
        }else{
            if chooseAllBtn == true{
                let newsModel =  self.modelList?.infomations![indexPath.row]
                return newsModel!.cellType!.cellHeight()
                
            }else{
                return 100
            }
            
        }
        

    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        if indexPath.section == 0{
            let cell = tableView.dequeueReusableCellWithIdentifier("SpecialStarDetailHeadCell", forIndexPath: indexPath) as! SpecialStarDetailHeadCell
             cell.delegate = self
            let cellInfo = self.modelList
            cell.selectionStyle = UITableViewCellSelectionStyle.None
            cell.type = "1"
            cell.setCellContentWithCellInfo(cellInfo)
            return cell
        }else{
            if chooseAllBtn == true{
                let model = self.modelList?.infomations![indexPath.row]
                
                let cell = tableView.dequeueReusableCellWithIdentifier(model!.cellType.rawValue, forIndexPath: indexPath) as! NewsCell
                
                cell.newsModel = model
                
                return cell
                
            }else{
                let model = self.modelList?.recruitments![indexPath.row]
                
                let cell = tableView.dequeueReusableCellWithIdentifier("advertisesCell", forIndexPath: indexPath) as! advertisesCell
                
                cell.nameLbl.text = model!.title
                cell.addressLbl.text = String(format: "%@-%@",model!.unitarea, model!.unitaddress)
                cell.salaryLbl.text = model!.pay
                cell.requireLbl.text = model!.lift
                cell.unittagLbl.text = model!.unittag
                
                return cell

            }
        }
        
    }
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        let sectionHeaderHeight: CGFloat = topicsHeight
        if scrollView.contentOffset.y <= sectionHeaderHeight && scrollView.contentOffset.y >= 0 {
            scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0)
        }
        else if scrollView.contentOffset.y >= sectionHeaderHeight {
            scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0)
        }
        
    }
    
    // MARK: - Table view delegate
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
        
        if indexPath.section == 0{
            
        }else{
            if chooseAllBtn == true{
                if self.modelList?.infomations![indexPath.row].type == 4{
                    //特殊新闻
                    let sb = UIStoryboard(name: "NewsList", bundle: nil)
                    let vc = sb.instantiateViewControllerWithIdentifier("SpecialNewsController") as! SpecialNewsController
                    vc.newsModel = self.modelList?.infomations![indexPath.row]
                   self.navigationController?.pushViewController(vc, animated: true)
                }else if self.modelList?.infomations![indexPath.row].type == 5{
                    //视频新闻
                    let sb = UIStoryboard(name: "NewsList", bundle: nil)
                    let vc = sb.instantiateViewControllerWithIdentifier("DetaillNewsController") as! DetaillNewsController
                    vc.newsModel = self.modelList?.infomations![indexPath.row]
                    self.navigationController?.pushViewController(vc, animated: true)
                    
                }else if self.modelList?.infomations![indexPath.row].type == 6{
                    //直播新闻
                    let sb = UIStoryboard(name: "NewsList", bundle: nil)
                    let vc = sb.instantiateViewControllerWithIdentifier("DetaillNewsController") as! DetaillNewsController
                    vc.newsModel = self.modelList?.infomations![indexPath.row]
                    self.navigationController?.pushViewController(vc, animated: true)
                }else if self.modelList?.infomations![indexPath.row].type == 8{
                    //淘宝新闻
                    let sb = UIStoryboard(name: "NewsList", bundle: nil)
                    let vc = sb.instantiateViewControllerWithIdentifier("DetaillNewsController") as! DetaillNewsController
                    vc.newsModel = self.modelList?.infomations![indexPath.row]
                    self.navigationController?.pushViewController(vc, animated: true)
                }else{
                    //正常新闻
                    let sb = UIStoryboard(name: "NewsList", bundle: nil)
                    let vc = sb.instantiateViewControllerWithIdentifier("DetaillNewsController") as! DetaillNewsController
                    vc.newsModel = self.modelList?.infomations![indexPath.row]
                    self.navigationController?.pushViewController(vc, animated: true)
                }
                
            }
            if chooserecruitBtn == true {
                
                let vc = self.storyboard?.instantiateViewControllerWithIdentifier("JoinUsRecruitDetailVC") as! JoinUsRecruitDetailVC
                vc.id = (self.modelList?.recruitments![indexPath.row].id)!
                vc.type = "招聘"
                self.navigationController?.pushViewController(vc, animated: true)
                
                
            }

        }
        
    }

   //MARK:target
    func allBtnClicked(sender: UIButton){
       
        chooseAllBtn = true
        chooserecruitBtn = false
        self.tableView.reloadData()
    }
    func recruitBtnClicked(sender: UIButton){
       
        chooserecruitBtn = true
        chooseAllBtn = false
        self.tableView.reloadData()
    }
       //MARK:networking
    func getStarDetailInfo(id: String){
        DataTool.specialStarDetail(id,completionHandler: { (newModel) in
            guard let newDataes = newModel else {
                return
            }
            print(newDataes)
            self.modelList = newDataes
           
            
        })

    }
    //收藏专业产品
    func getSpecitalCollection(){
        if self.modelList?.isshoucang == true{
            self.isshoucang = false
        }else{
            self.isshoucang = true
        }
        let urlStr = String(format: "%@user/mxqy/shoucang",BaseUrl)
        DataTool.specialProductCollection((self.modelList?.id)!,url: urlStr, isshoucang: self.isshoucang!,completionHandler: { (newModel) in
            guard newModel != nil else {
                return
            }
            self.msg = newModel
            self.getStarDetailInfo((self.modelList?.id)!)
           
            SVProgressHUD.showSuccessWithStatus(self.msg?.msg)
        })
        
    }


    
}
